<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>🎈 打气球游戏</title>
    <style>
        body {
            text-align: center;
            background-color: #f0f8ff;
            font-family: Arial;
        }

        canvas {
            background-color: #fff;
            border: 2px solid #333;
            margin-top: 20px;
        }

        #info {
            margin-top: 10px;
            font-size: 18px;
        }

        #controls {
            margin-top: 20px;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            margin: 5px;
        }

        #result {
            font-size: 24px;
            color: green;
            margin-top: 20px;
            display: none;
        }

        #restartBtn {
            display: none;
        }
    </style>
</head>
<body>
<h2>🎈 打气球游戏</h2>
<div id="controls">
    <button id="startBtn">开始游戏</button>
    <button id="restartBtn">重新开始</button>
</div>
<canvas id="gameCanvas" width="600" height="400"></canvas>
<div id="info">
    ⏱️ 剩余时间：<span id="time">60</span> 秒 &nbsp;&nbsp;
    🎯 击落气球：<span id="kills">0</span>/5
</div>
<div id="result">🎉 挑战成功！</div>

<script>
    const canvas = document.getElementById("gameCanvas");
    const ctx = canvas.getContext("2d");

    const cannon = {
        x: canvas.width / 2 - 15,
        y: canvas.height - 30,
        width: 30,
        height: 20,
        speed: 6
    };

    let bullets = [];
    let balloons = [];
    let gameInterval;
    let timerInterval;
    let gameTime = 60;
    let kills = 0;
    let totalBalloons = 0;
    const maxBalloons = 5;
    const activeBalloonLimit = 3;
    const fixedBalloonY = 60;
    let isGameRunning = false;

    document.addEventListener("keydown", handleKeydown);

    function handleKeydown(e) {
        if (!isGameRunning) return;

        if (e.key === "ArrowLeft" && cannon.x > 0) {
            cannon.x -= cannon.speed;
        } else if (e.key === "ArrowRight" && cannon.x + cannon.width < canvas.width) {
            cannon.x += cannon.speed;
        } else if (e.code === "Space") {
            bullets.push({
                x: cannon.x + cannon.width / 2 - 2,
                y: cannon.y,
                width: 4,
                height: 10,
                speed: 7
            });
        }
    }

    function startGame() {
        document.getElementById("startBtn").style.display = "none";
        document.getElementById("restartBtn").style.display = "none";
        document.getElementById("result").style.display = "none";

        bullets = [];
        balloons = [];
        cannon.x = canvas.width / 2 - 15;
        gameTime = 60;
        kills = 0;
        totalBalloons = 0;
        isGameRunning = true;
        updateInfo();

        gameInterval = setInterval(updateGame, 30);
        timerInterval = setInterval(updateTimer, 1000);
    }

    function updateTimer() {
        gameTime--;
        document.getElementById("time").innerText = gameTime;

        if (gameTime <= 0) {
            endGame(false);
        }
    }

    function endGame(success) {
        isGameRunning = false;
        clearInterval(gameInterval);
        clearInterval(timerInterval);

        const resultDiv = document.getElementById("result");
        if (success) {
            resultDiv.innerText = "🎉 挑战成功！";
            resultDiv.style.color = "green";
        } else {
            resultDiv.innerText = "❌ 游戏失败！";
            resultDiv.style.color = "red";
        }

        resultDiv.style.display = "block";
        document.getElementById("restartBtn").style.display = "inline-block";
    }

    function updateInfo() {
        document.getElementById("kills").innerText = kills;
        document.getElementById("time").innerText = gameTime;
    }

    function updateGame() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 大炮
        ctx.fillStyle = "black";
        ctx.fillRect(cannon.x, cannon.y, cannon.width, cannon.height);

        // 子弹
        bullets.forEach(b => {
            b.y -= b.speed;
            ctx.fillStyle = "blue";
            ctx.fillRect(b.x, b.y, b.width, b.height);
        });
        bullets = bullets.filter(b => b.y > 0);

        // 生成气球（不超限）
        if (balloons.length < activeBalloonLimit && totalBalloons < maxBalloons) {
            balloons.push(createBalloon());
            totalBalloons++;
        }

        // 移动 & 画气球
        balloons.forEach(balloon => {
            balloon.x += balloon.speed;

            if (balloon.x > canvas.width) {
                balloon.x = -40; // 继续循环移动
            }

            // 气球体
            ctx.beginPath();
            ctx.fillStyle = balloon.color;
            ctx.ellipse(balloon.x + 20, fixedBalloonY + 30, 20, 30, 0, 0, Math.PI * 2);
            ctx.fill();

            // 血条
            ctx.fillStyle = "green";
            ctx.fillRect(balloon.x, fixedBalloonY, 40 * (balloon.health / 3), 5);
        });

        // 子弹和气球碰撞
        bullets.forEach(bullet => {
            balloons.forEach(balloon => {
                if (
                    bullet.x < balloon.x + 40 &&
                    bullet.x + bullet.width > balloon.x &&
                    bullet.y < fixedBalloonY + 60 &&
                    bullet.y + bullet.height > fixedBalloonY
                ) {
                    bullet.hit = true;
                    balloon.health--;
                    if (balloon.health <= 0 && !balloon.killed) {
                        balloon.killed = true;
                        kills++;
                        gameTime += 10;
                        updateInfo();
                    }
                }
            });
        });

        bullets = bullets.filter(b => !b.hit);
        balloons = balloons.filter(b => !b.killed);

        // 判断胜利
        if (kills >= maxBalloons) {
            endGame(true);
        }
    }

    function createBalloon() {
        const types = [
            { color: "red", speed: 1.0 },
            { color: "yellow", speed: 1.4 },
            { color: "blue", speed: 1.8 }
        ];
        const type = types[Math.floor(Math.random() * types.length)];

        return {
            x: -40,
            y: fixedBalloonY,
            speed: type.speed,
            color: type.color,
            health: 3,
            killed: false
        };
    }

    // 绑定按钮事件
    document.getElementById("startBtn").addEventListener("click", startGame);
    document.getElementById("restartBtn").addEventListener("click", startGame);
</script>
</body>
</html>
